<template>
  <div class="" id="shopp-manager" v-loading="spinShow">
    <pages-header
        ref="pageHeader"
        :title="$route.params.id ? '编辑病种' : '添加病种'"
        :backUrl="$routeProStr + '/medical/disease_list'"
    ></pages-header>
    <el-card :bordered="false" shadow="never" class="mt16" :body-style="{ padding: '0 20px 20px' }">
      <el-form
          class="formValidate mt20"
          ref="formValidate"
          :rules="ruleValidate"
          :model="formValidate"
          :label-width="labelWidth"
          :label-position="labelPosition"
          @submit.native.prevent
      >
        <!-- 规格库存-->
        <el-row :gutter="24">

          <el-col :span="24">
            <el-form-item label="上级病种：" prop="pid">
              <el-switch v-model="formValidate.hasPid"></el-switch>
              <el-select v-model="formValidate.pid" placeholder="请选择" v-if="formValidate.hasPid" style="margin-left: 20px;">
                <el-option
                    v-for="item in parentDiseaseList"
                    :key="parseInt(item.id)"
                    :label="item.name"
                    :value="parseInt(item.id)">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="病种名称：" prop="name">
              <el-input class="content_width" v-model.trim="formValidate.name" placeholder="请输入病种名称" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="图片：">
              <div class="pictrueBox" @click="modalPicTap('dan', 'danTable', 0)">
                <div class="pictrue" v-if="formValidate.image">
                  <img v-lazy="formValidate.image" />
                  <el-input v-model="formValidate.image" style="display: none"></el-input>
                </div>
                <div class="upLoad acea-row row-center-wrapper" v-else>
                  <el-input v-model="formValidate.image" style="display: none"></el-input>
                  <i class="el-icon-picture-outline" style="font-size: 24px"></i>
                </div>
              </div>
            </el-form-item>
          </el-col>
          <!-- 多规格添加-->
          <el-col :span="24" class="noForm">
<!--            <el-form-item v-if="createBnt">-->
<!--              <el-button type="success" @click="generate()">立即生成</el-button>-->
<!--            </el-form-item>-->
            <!-- </el-col> -->
            <el-col :span="24" v-if="showIput">
              <el-col :xl="6" :lg="9" :md="10" :sm="24" :xs="24">
                <el-form-item label="规格：">
                  <el-input placeholder="请输入规格" v-model="formDynamic.attrsName" />
                </el-form-item>
              </el-col>
              <el-col :xl="6" :lg="9" :md="10" :sm="24" :xs="24">
                <el-form-item label="规格值：">
                  <el-input v-model="formDynamic.attrsVal" placeholder="请输入规格值" />
                </el-form-item>
              </el-col>
              <el-col :xl="6" :lg="5" :md="10" :sm="24" :xs="24">
                <div class="df-n-warp">
                  <el-button type="primary" @click="createAttrName">确定</el-button>
                  <el-button @click="offAttrName">取消</el-button>
                </div>
              </el-col>
            </el-col>
            <!-- 多规格设置-->
            <el-form-item label="治疗程度：" class="labeltop">
              <el-table :data="manyFormValidate" border>
                <el-table-column
                    :label="item.title"
                    :min-width="item.minWidth"
                    v-for="(item, index) in formValidate.header"
                    :key="index"
                >
                  <template slot-scope="scope">
                    <template v-if="item.key">
                      <div>
                        <span>{{ scope.row[item.key] }}</span>
                      </div>
                    </template>
                    <template v-else-if="item.slot === 'status'">
                      <el-switch
                          :controls="false"
                          :active-value="1"
                          :inactive-value="0"
                          v-model="manyFormValidate[scope.$index].status"
                          :value="manyFormValidate[scope.$index].status"
                          size="large"
                      >
                      </el-switch>
                    </template>
                    <template v-else-if="item.slot === 'price'">
                      <el-input-number
                          :controls="false"
                          v-model="manyFormValidate[scope.$index].price"
                          :min="0"
                          :max="9999999999"
                          class="priceBox"
                      ></el-input-number>
                    </template>
                    <template v-else-if="item.slot === 'action'">
                      <a @click="delAttrTable(scope.$index)">删除</a>
                    </template>
                  </template>
                </el-table-column>
              </el-table>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item>
          <el-button
              type="primary"
              :disabled="openSubimit"
              class="submission"
              @click="handleSubmit('formValidate')"
          >保存</el-button
          >
        </el-form-item>
      </el-form>
      <el-dialog :visible.sync="modalPic" width="950px" scrollable title="上传病种图" :close-on-click-modal="false">
        <uploadPictures
            :isChoice="isChoice"
            @getPic="getPic"
            :gridBtn="gridBtn"
            :gridPic="gridPic"
            v-if="modalPic"
        ></uploadPictures>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
import { mapState } from 'vuex';
import vuedraggable from 'vuedraggable';
import uploadPictures from '@/components/uploadPictures';
import {
  generateAttrApi,
  diseaseInfoApi,
  diseaseAddApi,
  diseaseGetRuleApi,
  getParentDiseases,
} from '@/api/medical';
import Setting from '@/setting';
import { getCookies } from '@/libs/util';

export default {
  name: 'medical_diseaseAdd',
  components: {
    // VueUeditorWrap,
    uploadPictures,
    draggable: vuedraggable,
  },
  data() {
    return {
      labelShow: false,
      dataLabel: [],
      seletVideo: 0, //选择视频类型
      customBtn: false, //自定义留言开关
      content: '',
      contents: '',
      fileUrl: Setting.apiBaseURL + '/file/upload',
      fileUrl2: Setting.apiBaseURL + '/file/video_upload',
      cardUrl: Setting.apiBaseURL + '/file/upload/1',
      upload_type: '', //视频上传类型 1 本地上传 2 3 4 OSS上传
      uploadData: {}, // 上传参数
      header: {},
      type: 0,
      modals: false,
      goods_modals: false,
      spinShow: false,
      openSubimit: false,
      virtualData: '',
      virtualList: [
        {
          key: '',
          value: '',
        },
      ],
      grid2: {
        xl: 10,
        lg: 12,
        md: 12,
        sm: 24,
        xs: 24,
      },
      grid3: {
        xl: 18,
        lg: 18,
        md: 20,
        sm: 24,
        xs: 24,
      },
      // 批量设置表格data
      oneFormBatch: [
        {
          price: 0,
        },
      ],
      // 规格数据
      formDynamic: {
        attrsName: '',
        attrsVal: '',
      },
      disk_type: 1, //卡密类型
      tabIndex: 0,
      tabName: '',
      formDynamicNameData: [],
      isBtn: false,
      columns: [],
      columnsInstall: [],
      columnsInstal2: [],
      gridPic: {
        xl: 6,
        lg: 8,
        md: 12,
        sm: 12,
        xs: 12,
      },
      gridBtn: {
        xl: 4,
        lg: 8,
        md: 8,
        sm: 8,
        xs: 8,
      },
      //自定义留言下拉选择
      CustomList: [
        {
          value: 'text',
          label: '文本框',
        },
        {
          value: 'number',
          label: '数字',
        },
        {
          value: 'data',
          label: '日期',
        },
        {
          value: 'time',
          label: '时间',
        },
        {
          value: 'phone',
          label: '手机号',
        },
        {
          value: 'img',
          label: '图片',
        },
      ],
      customess: {
        content: [],
      }, //自定义留言内容

      formValidate: {
        recommend: [], //病种推荐
        is_limit: false,
        limit_type: 0,
        limit_num: 0,
        hasPid: false,
        pid: '',
        name: '',
        image: '',
        status: 1,
        id: 0,
        attrs: [],
        items: [
          {
            pic: '',
            price: 0,
            cost: 0,
            ot_price: 0,
            stock: 0,
            bar_code: '',
          },
        ],
        header: [],
      },
      ruleList: [],
      templateList: [],
      createBnt: true,
      showIput: false,
      manyFormValidate: [],
      // 单规格表格data
      oneFormValidate: [
        {
          price: 0,
        },
      ],
      images: [],
      imagesTable: '',
      grid: {
        xl: 8,
        lg: 8,
        md: 12,
        sm: 24,
        xs: 24,
      },
      loading: false,
      modalPic: false,
      template: false,
      uploadList: [],
      treeSelect: [],
      picTit: '',
      tableIndex: 0,
      ruleValidate: {
        name: [{ required: true, message: '请输入病种名称', trigger: 'blur' }],
        image: [
          {
            required: true,
            message: '请上传病种图片',
            type: 'array',
            trigger: 'change',
          },
        ],
      },
      manyBrokerage: 0,
      manyBrokerageTwo: 0,
      manyVipPrice: 0,
      upload: {
        videoIng: false, // 是否显示进度条；
      },
      videoIng: false, // 是否显示进度条；
      progress: 0, // 进度条默认0
      attrs: [],
      couponName: [],
      updateIds: [],
      updateName: [],
      couponIds: '',
      couponNames: [],
      columnsInstalM: [],
      moveIndex: '',
      parentDiseaseList: [],
    };
  },
  computed: {
    ...mapState('media', ['isMobile']),
    labelWidth() {
      return this.isMobile ? undefined : '120px';
    },
    labelPosition() {
      return this.isMobile ? 'top' : 'right';
    },
    labelBottom() {
      return this.isMobile ? undefined : '15px';
    },
  },
  beforeRouteUpdate(to, from, next) {
    this.bus.$emit('onTagsViewRefreshRouterView', this.$route.path);
    next();
  },
  created() {
    this.getToken();
  },
  mounted() {
    if (this.$route.params.id !== '0' && this.$route.params.id) {
      this.getInfo();
    }
    if (this.$route.query.type) {
      this.modals = true;
      this.type = this.$route.query.type;
    } else {
      this.type = 0;
    }
    this.getParentDiseases()
    this.diseaseGetRule();
  },
  methods: {
    // 病种详情
    getEditorContent(data) {
      this.content = data;
    },
    cancel() {
      this.modals = false;
    },
    // 上传头部token
    getToken() {
      this.header['Authori-zation'] = 'Bearer ' + getCookies('token');
    },
    // 初始化数据展示
    infoData(data, isCopy) {
      this.attrs = data.items || [];
      if(data.pid !== 0){
        data.hasPid = true;
      }
      this.formValidate = data;
      this.seletVideo = data.seletVideo;
      this.formValidate.header = [];
      this.generate(isCopy, data.attrs);
      this.createBnt = true;
      this.oneFormValidate = [
        {
          price: 0,
        },
      ];
    },
    //关闭淘宝弹窗并生成数据；
    onClose(data) {
      this.modals = false;
      this.infoData(data, 1);
    },

    checkMove(evt) {
      this.moveIndex = evt.draggedContext.index;
    },
    end() {
      this.moveIndex = '';
      this.generate();
    },
    // 属性弹窗回调函数；
    userSearchs() {
      this.diseaseGetRule();
    },
    // 清空批量规格信息
    batchDel() {
      this.oneFormBatch = [
        {
          price: 0,
        },
      ];
    },
    confirm() {
      let that = this;
      that.createBnt = true;
      if (that.formValidate.selectRule.trim().length <= 0) {
        return that.$message.error('请选择属性');
      }
      that.ruleList.forEach(function (item, index) {
        if (item.rule_name === that.formValidate.selectRule) {
          that.attrs = item.rule_value;
        }
      });
    },
    // 获取父级病种列表
    getParentDiseases() {
      getParentDiseases().then((res) => {
        this.parentDiseaseList = res.data.list;
      });
    },
    // 获取病种属性模板；
    diseaseGetRule() {
      diseaseGetRuleApi().then((res) => {
        this.ruleList = res.data;
        if(undefined == this.$route.params.id){
          this.attrs = this.ruleList[0].rule_value;
          this.generate()
        }
      });
    },
    // 删除表格中的属性
    delAttrTable(index) {
      this.manyFormValidate.splice(index, 1);
    },
    // 批量添加
    batchAdd() {
      for (let val of this.manyFormValidate) {
        if (this.oneFormBatch[0].price > 0) {
          this.$set(val, 'price', this.oneFormBatch[0].price);
        }
      }
    },
    // 立即生成
    generate(isCopy, arr) {
      // this.attrs = this.ruleList[0].rule_value;
      generateAttrApi(
          {
            attrs: this.attrs,
          },
          this.formValidate.id,
      )
          .then((res) => {
            let info = res.data.info,
                header1 = JSON.parse(JSON.stringify(info.header));
            if (this.$route.params.id !== '0' && !isCopy) {
              this.manyFormValidate = info.value;
            }
            if (isCopy) {
              this.manyFormValidate = arr;
            }
            this.formValidate.header = header1;
            this.columnsInstalM = info.header;
            if (!this.$route.params.id && this.formValidate.spec_type === 1 && !isCopy) {
              this.manyFormValidate.map((item) => {
                item.pic = this.formValidate.image;
              });
              this.oneFormBatch[0].pic = this.formValidate.image;
            } else if (this.$route.params.id) {
              this.manyFormValidate.map((item) => {
                if (!item.pic) {
                  item.pic = this.formValidate.image;
                }
              });
              this.oneFormBatch[0].pic = this.formValidate.image;
            }
          })
          .catch((res) => {
            this.$message.error(res.msg);
          });
    },
    // 取消
    offAttrName() {
      this.showIput = false;
      this.createBnt = true;
    },
    clearAttr() {
      this.formDynamic.attrsName = '';
      this.formDynamic.attrsVal = '';
    },
    // 删除规格
    handleRemoveRole(index) {
      this.attrs.splice(index, 1);
      this.manyFormValidate.splice(index, 1);
    },
    // 删除属性
    handleRemove2(item, index) {
      item.splice(index, 1);
    },
    // 添加规则名称
    createAttrName() {
      if (this.formDynamic.attrsName && this.formDynamic.attrsVal) {
        let data = {
          value: this.formDynamic.attrsName,
          detail: [this.formDynamic.attrsVal],
        };
        this.attrs.push(data);
        var hash = {};
        this.attrs = this.attrs.reduce(function (item, next) {
          /* eslint-disable */
          hash[next.value] ? '' : (hash[next.value] = true && item.push(next));
          return item;
        }, []);
        this.clearAttr();
        this.showIput = false;
        this.createBnt = true;
      } else {
        this.$message.warning('请添加完整的规格！');
      }
    },
    // 改变规格
    changeSpec() {
      this.formValidate.is_sub = [];
    },
    // 详情
    getInfo() {
      let that = this;
      that.spinShow = true;
      diseaseInfoApi(that.$route.params.id)
          .then(async (res) => {
            let data = res.data.diseaseInfo;
            // 临时处理方案
            this.infoData(data);
            this.spinShow = false;
          })
          .catch((res) => {
            this.spinShow = false;
            this.$message.error(res.msg);
          });
    },
    handleRemove(i) {
      this.images.splice(i, 1);
      this.formValidate.slider_image.splice(i, 1);
      this.oneFormValidate[0].pic = this.formValidate.slider_image[0];
    },
    // 关闭图片上传模态框
    changeCancel(msg) {
      this.modalPic = false;
    },
    // 点击病种图
    modalPicTap(tit, picTit, index) {
      this.modalPic = true;
      this.isChoice = tit === 'dan' ? '单选' : '多选';
      this.picTit = picTit;
      this.tableIndex = index;
    },
    // 获取单张图片信息
    getPic(pc) {
      switch (this.picTit) {
        case 'danFrom':
          this.formValidate.image = pc.att_dir;
          if (!this.$route.params.id) {
            if (this.formValidate.spec_type === 0) {
              this.oneFormValidate[0].image = pc.att_dir;
            } else {
              this.manyFormValidate.map((item) => {
                item.image = pc.att_dir;
              });
              this.oneFormBatch[0].image = pc.att_dir;
            }
          }
          break;
        case 'danTable':
          this.formValidate.image = pc.att_dir;
          break;
        case 'duopi':
          this.oneFormBatch[this.tableIndex].image = pc.att_dir;
          break;
        case 'recommend_image':
          this.formValidate.recommend_image = pc.att_dir;
          break;
        default:
          this.manyFormValidate[this.tableIndex].image = pc.att_dir;
      }
      this.modalPic = false;
    },
    // 提交
    handleSubmit(name) {
      this.$refs[name].validate((valid) => {
        if (valid) {
          this.formValidate.type = this.type;
          this.formValidate.items = this.attrs;
          this.formValidate.attrs = this.manyFormValidate;
          this.formValidate.is_copy = 1;
          if (this.formValidate.spec_type === 1 && this.manyFormValidate.length === 0) {
            return this.$message.warning('病种信息-请点击生成多规格');
            // return this.$message.warning('请点击生成规格！');
          }
          if (this.openSubimit) return;
          this.openSubimit = true;
          this.formValidate.description = this.formatRichText(this.content);
          diseaseAddApi(this.formValidate)
              .then(async (res) => {
                this.openSubimit = false;
                this.$message.success(res.msg);
                setTimeout(() => {
                  this.openSubimit = false;
                  this.$router.push({ path: this.$routeProStr + '/medical/disease_list' });
                }, 500);
              })
              .catch((res) => {
                setTimeout((e) => {
                  this.openSubimit = false;
                }, 1000);
                this.$message.error(res.msg);
              });
        } else {
          if (!this.formValidate.name) {
            return this.$message.warning('病种信息-病种名称不能为空');
          }
        }
      });
    },
    changeTemplate(msg) {
      this.template = msg;
    },
    // 表单验证
    validate(prop, status, error) {
      if (status === false) {
        this.$message.warning(error);
      }
    },
    // 移动
    handleDragStart(e, item) {
      this.dragging = item;
    },
    handleDragEnd(e, item) {
      this.dragging = null;
    },
    handleDragOver(e) {
      e.dataTransfer.dropEffect = 'move';
    },
    handleDragEnter(e, item) {
      e.dataTransfer.effectAllowed = 'move';
      if (item === this.dragging) {
        return;
      }
      const newItems = [...this.formValidate.slider_image];
      const src = newItems.indexOf(this.dragging);
      const dst = newItems.indexOf(item);
      newItems.splice(dst, 0, ...newItems.splice(src, 1));
      this.formValidate.slider_image = newItems;
    },
    // 过滤详情内容
    formatRichText(html) {
      let newContent = html.replace(/<img[^>]*>/gi, function (match, capture) {
        match = match.replace(/style="[^"]+"/gi, '').replace(/style='[^']+'/gi, '');
        match = match.replace(/width="[^"]+"/gi, '').replace(/width='[^']+'/gi, '');
        match = match.replace(/height="[^"]+"/gi, '').replace(/height='[^']+'/gi, '');
        return match;
      });
      newContent = newContent.replace(/style="[^"]+"/gi, function (match, capture) {
        match = match.replace(/width:[^;]+;/gi, 'max-width:100%;').replace(/max-max-width:[^;]+;/gi, 'max-width:100%;')
        return match;
      });
      newContent = newContent.replace(/<br[^>]*\/>/gi, '');
      newContent = newContent.replace(
          /\<img/gi,
          '<img style="max-width:100%;height:auto;display:block;margin-top:0;margin-bottom:0;"',
      );
      return newContent;
    },
    //对象数组去重；
    unique(arr) {
      const res = new Map();
      return arr.filter((arr) => !res.has(arr.product_id) && res.set(arr.product_id, 1));
    },
    // 病种id
    getProductId(data) {
      this.goods_modals = false;
      this.formValidate.recommend_list = this.unique(this.formValidate.recommend_list.concat(data));
    },
    // 选择用户标签
    activeData(dataLabel) {
      this.labelShow = false;
      this.dataLabel = dataLabel;
    },
    // 标签弹窗关闭
    labelClose() {
      this.labelShow = false;
    },
    // 删除用户标签
    closeLabel(label) {
      let index = this.dataLabel.indexOf(this.dataLabel.filter((d) => d.id == label.id)[0]);
      this.dataLabel.splice(index, 1);
    },
    uniques(songs) {
      let result = {};
      let finalResult = [];
      for (let i = 0; i < songs.length; i++) {
        result[songs[i].product_id] = songs[i];
      }
      for (let item in result) {
        finalResult.push(result[item]);
      }
      return finalResult;
    },
    handleRemoveRecommend(i) {
      this.formValidate.recommend_list.splice(i, 1);
    },
  },
};
</script>
<style scoped lang="stylus">
::v-deep .el-tabs__item {
  height: 54px !important;
  line-height: 54px !important;
}

.content_width {
  width: 460px;
}

.list-group {
  margin-left: -8px;
}


.drag {
  cursor: move;
  margin: 3px 0
}

.move-icon {
  width: 30px;
  cursor: move;
  margin-right: 10px;
}

.move-icon .icondrag2 {
  font-size: 26px;
  color: #d8d8d8;
}

.maxW ::v-deep .ivu-select-dropdown {
  max-width: 600px;
}

#shopp-manager .ivu-table-wrapper {
  border-left: 1px solid #dcdee2;
  border-top: 1px solid #dcdee2;
}


#shopp-manager .ivu-form-item {
  position: relative;
}

#shopp-manager .ivu-form-item .tips {
  position: absolute;
  color: #999;
  top: 29px;
  left: -77px;
  font-size: 12px;
}


.submission {
  margin-left: 10px;
}

.color-list .tip {
  color: #c9c9c9;
  font-size: 12px;
}

.color-list .color-item {
  height: 30px;
  line-height: 30px;
  padding: 0 10px;
  color: #fff;
  margin-right: 10px;
  font-size: 12px;

}

.color-list .color-item.blue {
  background-color: #1E9FFF;
}

.color-list .color-item.yellow {
  background-color: rgb(254, 185, 0);
}

.color-list .color-item.green {
  background-color: #009688;
}

.color-list .color-item.red {
  background-color: #ed4014;
}

.columnsBox {
  margin-right: 10px;
  width: 200px;
}

.priceBox {
  width: 100%;
}

.rulesBox {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  .item{
    display:flex;
  }
}

.pictrueBox {
  display: inline-block;
}

.pictrueTab {
  width: 40px !important;
  height: 40px !important;
}

.pictrue {
  width: 60px;
  height: 60px;
  border: 1px dotted rgba(0, 0, 0, 0.1);
  margin-right: 15px;
  display: inline-block;
  position: relative;
  cursor: pointer;

  img {
    width: 100%;
    height: 100%;
  }

  .btndel {
    position: absolute;
    z-index: 1;
    width: 20px !important;
    height: 20px !important;
    left: 46px;
    top: -4px;
  }
}

.upLoad {
  width: 58px;
  height: 58px;
  line-height: 58px;
  border: 1px dotted rgba(0, 0, 0, 0.1);
  border-radius: 4px;
  background: rgba(0, 0, 0, 0.02);
  cursor: pointer;
}
</style>
